package ai.zixing.mashibing.advance_class.secend.class01;

/**
 * 转圈打印矩阵
 */
public class Code05_PrintMatrixSpiralOrder {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        // 1 2 3 4 8 12 11 10 9 5 6 7
        spiralOrderPrint(matrix);
    }

    private static void spiralOrderPrint(int[][] matrix) {
        int aR = 0;
        int aC = 0;
        int bR = matrix.length - 1;
        int bC = matrix[0].length - 1;
        while (aR <= bR && aC <= bC) {
            printEdge(matrix, aR++, aC++, bR--, bC--);
        }
    }

    // m 矩阵
    // (a, b) 左上角位置
    // (c, d) 右下角位置
    private static void printEdge(int[][] m, int a, int b, int c, int d) {
        // 是一条横线或者中点
        if (a == c) {
            for (int i = a; i <= d ; i++) {
                System.out.print(m[a][i] + " ");
            }
        }
        // 是一条竖线
        else if (b == d) {
            for (int i = a; i <= c; i++) {
                System.out.print(m[i][b] + " ");
            }
        } else {
            // 是个框，则打印四个边
            // 当前打印店的坐标
            int curR = a;
            int curC = b;
            while (curC < d) {
                System.out.print(m[a][curC++] + " ");
            }
            while (curR < c) {
                System.out.print(m[curR++][d] + " ");
            }
            while (curC > a) {
                System.out.print(m[c][curC--] + " ");
            }
            while (curR > b) {
                System.out.print(m[curR--][a] + " ");
            }
        }
    }
}
